<template>
  <div class="traceability-detail">
    <div class="page-header">
      <h1>产品溯源详情</h1>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <div v-else-if="error" class="error-container">
      <el-empty description="无法加载溯源信息" :image-size="200">
        <template #description>
          <p>{{ errorMessage }}</p>
        </template>
        <el-button type="primary" @click="fetchProductData">重试</el-button>
      </el-empty>
    </div>

    <div v-else class="product-info">
      <!-- 产品基本信息 -->
      <el-card class="product-card">
        <div class="product-header">
          <div class="product-image">
            <img :src="getImageUrl(productData.coverImage)" :alt="productData.goodsName">
          </div>
          <div class="product-details">
            <h2>{{ productData.goodsName }}</h2>
            <div class="product-meta">
              <p><strong>生产批次:</strong> {{ productData.productionBatch }}</p>
              <p><strong>保质期:</strong> {{ productData.shelfLifeDay }}天</p>
              <p><strong>生产许可证号:</strong> {{ productData.productionLicenseNumber }}</p>
              <p><strong>生产企业:</strong> {{ productData.manufacturer }}</p>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 养殖信息 -->
      <el-card v-if="farmingData" class="info-card">
        <template #header>
          <div class="card-header">
            <h3>养殖信息</h3>
          </div>
        </template>
        <div class="info-content">
          <div class="info-item">
            <span class="label">品种:</span>
            <span class="value">{{ farmingData.breed }}</span>
          </div>
          <div class="info-item">
            <span class="label">来源:</span>
            <span class="value">{{ farmingData.origin }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲养天数:</span>
            <span class="value">{{ farmingData.feedingDays }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲料品牌:</span>
            <span class="value">{{ farmingData.feedBrand }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲养负责人:</span>
            <span class="value">{{ farmingData.feedingSupervisor }}</span>
          </div>
          <div class="info-item">
            <span class="label">出栏时间:</span>
            <span class="value">{{ formatDate(farmingData.harvestDate) }}</span>
          </div>
        </div>

        <!-- 养殖企业信息 -->
        <div v-if="farmingCorporate" class="corporate-info">
          <h4>养殖企业信息</h4>
          <div class="info-item">
            <span class="label">养殖场:</span>
            <span class="value">{{ farmingCorporate.farmingAddtrss }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人:</span>
            <span class="value">{{ farmingCorporate.farmingPerson }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲养数量:</span>
            <span class="value">{{ farmingCorporate.farmingNum }}</span>
          </div>
        </div>

        <!-- 图片展示区域 -->
        <div v-if="farmingImages && farmingImages.length > 0" class="image-gallery">
          <h4>相关图片</h4>
          <div class="image-list">
            <div v-for="img in farmingImages" :key="img.id" class="image-item" @click="previewImage(img.imgUrl)">
              <img :src="getImageUrl(img.imgUrl)" :alt="img.imgName">
            </div>
          </div>
        </div>
      </el-card>

      <!-- 屠宰信息 -->
      <el-card v-if="slaughterData" class="info-card">
        <template #header>
          <div class="card-header">
            <h3>屠宰信息</h3>
          </div>
        </template>
        <div class="info-content">
          <div class="info-item">
            <span class="label">批次:</span>
            <span class="value">{{ slaughterData.batch }}</span>
          </div>
          <div class="info-item">
            <span class="label">到场均重:</span>
            <span class="value">{{ slaughterData.arrivalAverageWeight }}kg</span>
          </div>
          <div class="info-item">
            <span class="label">到场时间:</span>
            <span class="value">{{ formatDate(slaughterData.arrivalTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">屠宰时间:</span>
            <span class="value">{{ formatDate(slaughterData.slaughterTime) }}</span>
          </div>
        </div>

        <!-- 屠宰企业信息 -->
        <div v-if="slaughterCorporate" class="corporate-info">
          <h4>屠宰企业信息</h4>
          <div class="info-item">
            <span class="label">企业名称:</span>
            <span class="value">{{ slaughterCorporate.companyName }}</span>
          </div>
          <div class="info-item">
            <span class="label">企业地址:</span>
            <span class="value">{{ slaughterCorporate.companyArrdess }}</span>
          </div>
          <div class="info-item">
            <span class="label">成立时间:</span>
            <span class="value">{{ formatDate(slaughterCorporate.establishmentTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">企业简介:</span>
            <span class="value">{{ slaughterCorporate.companyProfile }}</span>
          </div>
        </div>

        <!-- 图片展示区域 -->
        <div v-if="slaughterImages && slaughterImages.length > 0" class="image-gallery">
          <h4>相关图片</h4>
          <div class="image-list">
            <div v-for="img in slaughterImages" :key="img.id" class="image-item" @click="previewImage(img.imgUrl)">
              <img :src="getImageUrl(img.imgUrl)" :alt="img.imgName">
            </div>
          </div>
        </div>
      </el-card>

      <!-- 深加工信息 -->
      <el-card v-if="deepProcessingData" class="info-card">
        <template #header>
          <div class="card-header">
            <h3>深加工信息</h3>
          </div>
        </template>
        <div class="info-content">
          <div class="info-item">
            <span class="label">加工班组:</span>
            <span class="value">{{ deepProcessingData.team }}</span>
          </div>
          <div class="info-item">
            <span class="label">班组负责人:</span>
            <span class="value">{{ deepProcessingData.leader }}</span>
          </div>
        </div>

        <!-- 深加工企业信息 -->
        <div v-if="deepProcessingCorporate" class="corporate-info">
          <h4>加工企业信息</h4>
          <div class="info-item">
            <span class="label">企业名称:</span>
            <span class="value">{{ deepProcessingCorporate.corporationName }}</span>
          </div>
          <div class="info-item">
            <span class="label">生产许可证号:</span>
            <span class="value">{{ deepProcessingCorporate.productionLicenseNumber }}</span>
          </div>
        </div>

        <!-- 图片展示区域 -->
        <div v-if="deepProcessingImages && deepProcessingImages.length > 0" class="image-gallery">
          <h4>相关图片</h4>
          <div class="image-list">
            <div v-for="img in deepProcessingImages" :key="img.id" class="image-item" @click="previewImage(img.imgUrl)">
              <img :src="getImageUrl(img.imgUrl)" :alt="img.imgName">
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { readB, uploadB } from '@/https/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'

const route = useRoute()
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('无法加载溯源信息')

// 产品数据
const productData = ref<any>({})
const farmingData = ref<any>(null)
const farmingCorporate = ref<any>(null)
const farmingImages = ref<any[]>([])
const slaughterData = ref<any>(null)
const slaughterCorporate = ref<any>(null)
const slaughterImages = ref<any[]>([])
const deepProcessingData = ref<any>(null)
const deepProcessingCorporate = ref<any>(null)
const deepProcessingImages = ref<any[]>([])

// 获取QR码ID
const qrCodeId = ref(route.query.id as string)

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return moment(dateString).format('YYYY年MM月DD日')
}

// 统一图片预览处理函数
const getImageUrl = (url: string) => {
  if (!url) return ''

  // 如果已经是完整URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 确保路径以斜杠开头
  const path = url.startsWith('/') ? url : '/' + url

  // 使用API基础URL构建完整URL
  return uploadB.defaults.baseURL + path
}

// 图片预览
const previewImage = (url: string) => {
  ElMessageBox.alert(
    `<div style="text-align:center"><img src="${getImageUrl(url)}" style="max-width:100%"></div>`,
    '图片预览',
    {
      dangerouslyUseHTMLString: true,
      showConfirmButton: false,
      showClose: true,
      closeOnClickModal: true,
      customClass: 'image-preview-dialog'
    }
  )
}

// 获取产品溯源数据
const fetchProductData = async () => {
  loading.value = true
  error.value = false

  try {
    if (!qrCodeId.value) {
      throw new Error('缺少溯源码ID参数')
    }

    // 获取产品基本信息
    const response = await readB.get('/TraceabilityMenganment/GetTraceabilityDetail', {
      params: { qrCodeId: qrCodeId.value }
    })

    if (response.data.code !== 200) {
      throw new Error(response.data.message || '获取溯源信息失败')
    }

    const data = response.data.data

    // 设置产品基本信息
    productData.value = data.productInfo || {}

    // 设置养殖信息
    farmingData.value = data.farmingInfo || null
    farmingCorporate.value = data.farmingCorporate || null
    farmingImages.value = data.farmingImages || []

    // 设置屠宰信息
    slaughterData.value = data.slaughterInfo || null
    slaughterCorporate.value = data.slaughterCorporate || null
    slaughterImages.value = data.slaughterImages || []

    // 设置深加工信息
    deepProcessingData.value = data.deepProcessingInfo || null
    deepProcessingCorporate.value = data.deepProcessingCorporate || null
    deepProcessingImages.value = data.deepProcessingImages || []

  } catch (err: any) {
    error.value = true
    errorMessage.value = err.message || '获取溯源信息失败'
    ElMessage.error(errorMessage.value)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProductData()
})
</script>

<style scoped>
.traceability-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.loading-container,
.error-container {
  padding: 40px 0;
}

.product-card {
  margin-bottom: 20px;
}

.product-header {
  display: flex;
  gap: 20px;
}

.product-image {
  width: 120px;
  height: 120px;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-details h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 20px;
}

.product-meta {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.product-meta p {
  margin: 0;
  font-size: 14px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.info-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.corporate-info {
  margin-top: 20px;
  margin-bottom: 20px;
}

.corporate-info h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #555;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.label {
  font-size: 14px;
  color: #666;
}

.value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.image-gallery {
  margin-top: 20px;
}

.image-gallery h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #555;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;
}

.image-item {
  width: 100%;
  aspect-ratio: 1;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #eee;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .traceability-detail {
    padding: 10px;
  }

  .product-header {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: auto;
    max-height: 200px;
    margin-bottom: 10px;
  }

  .info-content {
    grid-template-columns: 1fr;
  }
}
</style>

<style>
/* 全局样式 */
.image-preview-dialog {
  max-width: 90vw !important;
}

.image-preview-dialog .el-message-box__content {
  padding: 10px;
  max-height: 80vh;
  overflow: auto;
}
</style>